import { defineStore } from "pinia";

import { login, getInfo, outLogin } from "@/api/auth.js";
import router from "../router";

export const useUserStore = defineStore("user", {
    persist: true, // 开启持久化存储
    state: () => ({
        token: null,
        userInfo: null
    }),
    actions: {
        accountLogin(formData, loading) {
            loading.value = true;
            login(formData).then((res) => {
                if (res.code == 200) {
                    this.token = res.result.token;

                    getInfo().then((userRes) => {
                        if (userRes.code == 200) {
                            this.userInfo = userRes.result;
                            router.push("/");
                        }
                    });
                }

                loading.value = false;
            });
        },
        outLogin() {
            outLogin().then(res => {
                this.token = null;
                this.userInfo = null;
                router.push("/login");
            })
        }
    },
});